<template>
  <div style="margin-left: 0">
    <el-row :gutter="24">
      <el-col v-if="!code" :span="24">
        <el-tag v-for="(item, index) in relateItems" :key="item.label" closable effect="dark" @close="delRelateItem(index)" style="margin: 0 5px 5px 0">{{ item.label }}</el-tag>
      </el-col>
      <el-col v-if="!code" :span="24" style="margin-bottom: 20px;">
        <el-select v-model="currentFirst" placeholder="模块" size="small" value-key="id" @change="loadSecondData">
          <el-option v-for="item in relateList" :key="item.id" :value="item" :label="item.label"/>
        </el-select>
        <el-select v-model="currentSecond" placeholder="请选择" size="small" value-key="id" style="margin: 0 10px;"
                   :remote="true" :remote-method="secondSearch" :loading="secondLoading"
                   :disabled="!(currentFirst && currentFirst.id)" @change="secondChange" filterable>
          <el-option v-for="item in secondList" :key="item.id" :value="item" :label="item.name"/>
        </el-select>
        <el-select
            v-model="currentThird"
            placeholder="请选择"
            size="small"
            value-key="id"
            v-show="currentFirst.moduleCode === 'Customer'"
            :disabled="!(currentSecond && currentSecond.id)"
            filterable
            :remote="true"
            :remote-method="thirdSearch"
            :loading="thirdLoading"
            @change="formatData">
          <el-option v-for="item in thirdList" :key="item.id" :value="item" :label="item.name"/>
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-select v-model="sourceType" class="m-2" placeholder="类型" size="small" @change="selectSourceType" style="width: 100%">
          <el-option label="文档" :value="1">文档</el-option>
          <el-option label="附件" :value="2">附件</el-option>
        </el-select>
      </el-col>
      <el-col :span="5" v-if="sourceType == 1" style="display: flex; align-items: center;">
        <el-select v-model="classId" class="m-2" placeholder="主要分类" size="small" @change="selectClass">
          <el-option v-for="item in fileClassList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
        <i class="fa fa-plus-square" style="font-size: 20px; margin-left: 8px;" @click="openFileClass"></i>
      </el-col>
      <el-col :span="5">
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            style="width: 180px; display: flex;"
            :action="action"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleSuccess">
          <el-button type="primary" style="width: 180px;">文 件 上 传</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-table :data="tableList" height="250" style="width: 95%; margin-top:20px">
      <el-table-column prop="fileLogId" label="文件编号"/>
      <el-table-column prop="name" label="文件名称"/>
      <el-table-column prop="src" label="文件地址" max-width="180"/>
      <el-table-column v-if="code != null && code != ''" prop="code" label="来源">
        <template #default="scope">
          {{ codeDict[scope.row.code] }}
        </template>
      </el-table-column>
      <el-table-column prop="className" label="分类"/>
      <el-table-column prop="sourceType" label="类型">
        <template #default="scope">
          {{ scope.row.sourceType == 1 ? '文档' : '附件' }}
        </template>
      </el-table-column>
      <el-table-column prop="relevanceName" label="关联详情" max-width="180"/>
      <el-table-column v-if="code == null || code == ''" prop="modalList" label="关联">
        <template #default="scope">
          <div v-for="(item,index) in scope.row.modalList" :key="index">
            {{ codeDict[item.code] }}: {{ item.label }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <FileClass v-model:dialogDrawer="dialogFileClass" @onClose="activeClose"></FileClass>
  </div>
</template>

<script>
import {computed, onMounted, reactive, toRefs} from 'vue'
import {Session} from '/@/utils/storage'
import {ElMessage} from 'element-plus'
import {getRelateItems, getRelateDataList, getCustomerOrders} from '/@/api/matter'
import FileClass from '/@/components/fileClass/index.vue'
import api from '/@/api/commonApi'


export default {
  name: 'Document',
  props: {
    // 模块（钱、事、市、客...）
    code: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 事项（报告、合同、审批...）
    fileGroup: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 活动id、订单id、线索id、客id、品id...
    relevanceId: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 名称
    relevanceName: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 文件集合
    resultList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 最大上传数
    limit: {
      type: Number,
      default: 9
    }
  },
  components: {
    FileClass
  },
  emits: ['update:resultList'],
  setup(props, context) {
    const {code, relevanceId, relevanceName, fileGroup, resultList} = toRefs(props)
    const state = reactive({
      action: '/api/file/filaAttach/upload',
      headers: {
        '17work': Session.get('token')
      },
      uploadFiles: [],
      relateList: [],
      secondList: [],
      thirdList: [],
      relateItems: [],
      currentFirst: {}, // 拿整个对象
      currentSecond: {},
      secondLoading: false,
      thirdLoading: false,
      currentThird: {},
      secondParams: {
        current: 1,
        size: 999,
        name: null
      },
      thirdParams: {
        current: 1,
        size: 999,
        name: null,
        memberId: null
      },
      classId: '',
      className: '',
      sourceType: 1,
      fileClassList: [],
      dialogFileClass: false,
      modelList: [],
      fileList: [],
      tableList: [],
      codeDict: {}
    })

    // 选择模块
    const loadSecondData = (val) => {
      console.log(val);
      initData()
      if (val.identifyName) {
        getRelateDataList(val.identifyName, state.secondParams).then(res => state.secondList = state.secondList.concat(res.data.records))
      }
    }

    /**
     * 上传超出限制
     */
    const handleExceed = (files, uploadFiles) => {
      ElMessage.warning('已达到最大上传文件数量！')
    }
    /**
     * 移除
     */
    const handleRemove = (file, files) => {

    }
    /**
     * 预览文件
     */
    const handlePreview = (file) => {

    }
    /**
     * 上传成功
     */
    const handleSuccess = (res, file, files) => {
      const {name, src, fileLogId} = res.data
      let map = {
        name: name,
        src: src,
        code: code.value,
        fileGroup: fileGroup.value,
        classId: state.classId,
        className: state.className,
        sourceType: state.sourceType,
        fileLogId: fileLogId,
        relevanceId: relevanceId.value,
        relevanceName: relevanceName.value,
        modalList: []
      }
      state.modelList.forEach(item => {
        map.modalList.push(item)
      })
      state.tableList.push(map)
      context.emit('update:resultList', state.tableList)
    }
    // 获取模块列表
    const moduleList = () => {
      getRelateItems().then(res => state.relateList = res.data)
    }
    // 选择事项主键
    const secondSearch = (search) => {
      state.secondList = []
      state.secondParams.name = search
      loadSecondData(state.currentSecond)
    }
    const secondChange = (val) => {
      if (state.currentFirst.moduleCode === 'Customer') {
        state.thirdParams.memberId = val.id
        getCustomerOrders(state.thirdParams).then(res => {
          if (res.data.records.length > 0) {
            state.thirdList = res.data.records
          } else {
            ElMessage.warning('客户订单为空')
            formatData()
            state.currentSecond = {}
          }
        })
      } else {  // 直接提交已选数据到父组件
        formatData()
        state.currentSecond = {}
      }
    }
    const thirdSearch = (search) => {
      state.thirdList = []
      state.thirdParams.name = search
      getCustomerOrders(state.thirdParams).then(res => state.thirdList = res.data.records)
    }
    const formatData = () => {
      let itemArr = state.relateItems
      if (itemArr.length > 0) {
        let flag = false
        for (let i = 0; i < itemArr.length; i++) {
          flag = itemArr[i].agendaMatterRelatableId === state.currentFirst.id && itemArr[i].seRelateDataId === state.currentSecond.id
          if (state.currentThird.id) {
            flag = itemArr[i].thRelateDataId === state.currentThird.id
          }
          if (flag) {
            break
          }
        }
        if (flag) {
          return
        }
      }
      let item = {
        code: state.currentFirst.moduleCode,
        agendaMatterRelatableId: state.currentFirst.id,
        agendaMatterRelatableName: state.currentFirst.label,
        seRelateDataId: state.currentSecond.id,
        seRelateDataName: state.currentSecond.name,
        thRelateDataId: state.currentThird.id || null,
        thRelateDataName: state.currentThird.name || null,
        label: state.currentFirst.label + '/' + state.currentSecond.name + (state.currentThird.id ? ('/' + state.currentThird.name) : '')
      }
      itemArr.push(item)
      // context.emit('update:relateItems', itemArr)
      // context.emit('change', itemArr)
      state.modelList = JSON.parse(JSON.stringify(itemArr))
    }
    // 初始化
    const initData = () => {
      state.secondList = state.thirdList = []
      state.currentSecond = state.currentThird = {}
      state.thirdParams = {
        current: 1,
        size: 999,
        name: null,
        memberId: null
      }
      state.secondParams = {
        current: 1,
        size: 999,
        name: null
      }
    }
    // 分类列表
    const classList = () => {
      api.fileClassList().then(res => {
        state.fileClassList = res.data
      })
    }
    // 打开分类列表
    const openFileClass = () => {
      state.dialogFileClass = true
    }
    // 加载分类列表
    const activeClose = () => {
      classList()
    }
    // 选择分类
    const selectClass = e => {
      let list = JSON.parse(JSON.stringify(state.fileClassList))
      const result = list.find(item => {
        return item.id == e
      })
      state.className = result.name
    }
    // 选择来源
    const selectSourceType = e => {
      if (e == 1) {
        state.currentFirst = {}
        state.currentSecond = {}
        state.currentThird = {}
        state.relateItems = []
        state.classId = ''
        state.className = ''
      }
    }
    // 获取事项编码列表
    const matterCodeDict = () => {
      api.moduleCode().then(res => {
        state.codeDict = res.data
      })
    }

    onMounted(() => {
      moduleList()
      classList()
      matterCodeDict()
    })
    return {
      ...toRefs(state),
      handleExceed,
      handleRemove,
      handlePreview,
      handleSuccess,
      resultList,
      selectClass,
      moduleList,
      secondSearch,
      secondChange,
      thirdSearch,
      classList,
      formatData,
      activeClose,
      openFileClass,
      loadSecondData,
      selectSourceType
    }
  }
}

</script>

<style lang="scss" scoped></style>
